package cn.cwx.code.login.controller;

import cn.cwx.code.common.utils.SecurityUtils;
import cn.cwx.code.common.utils.UserState;
import cn.cwx.code.home.entity.User;
import cn.cwx.code.login.service.LoginService;

import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by GJ on 2017/6/21.
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    LoginService loginService;

    /**
     * @Author CWX
     * @Date 2017/6/21 18:20
     * @description 登陆成功 Session:"user-login",user
     */
    @RequestMapping
    public String userLogin(User user, HttpServletRequest httpServletRequest) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (user != null) {
            //判断前端传入的数据是否正确
            String password = SecurityUtils.md5Password(user.getPassword());
            if (password.equals("null")) {
                return "index";
            }
            user.setPassword(password);
            boolean result = loginService.findUser(user);
            if (result) {//登陆成功
                httpServletRequest.getSession().setAttribute("user-login", user);
                return "home";
            }
        }
        return "index";
    }

    /**
     * @Author CWX
     * @Date 2017/6/21 19:33
     * @description 用户注册
     */
    @RequestMapping("/login")
    public UserState loginUser(HttpServletRequest httpServletRequest ,User user, ModelAndView modelAndView) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		 String logString = (String)httpServletRequest.getAttribute("shiroLoginFailure");
    	   if (UnknownAccountException.class.getName().equals(logString)) {
			System.out.println("未知账户-------");
		}else {
			System.out.println("其它错误------");
		}
		 return null;
		/*
		 * String password = SecurityUtils.md5Password(user.getPassword());
		 * user.setPassword(password); UserState userState = loginService.login(user);
		 * return userState;
		 */
     
    }
}
